import muxjs from 'mux.js'
import URLToolkit from 'url-toolkit'
import { Parser } from 'm3u8-parser'

export default HLSDownloader

var video = document.querySelector('#video')

function HLSDownloader (url) {
    fetch(url)
        .then(response => {
            return response.text()
        })
        .then(text => {
            // console.log(text)
            var parser = new Parser()
            
            parser.push(text)
            parser.end()

            var parserdManifest = parser.manifest
            var segments = parserdManifest.segments
            var duration = parserdManifest.targetDuration

            // console.log(parserdManifest)
            return segments
        })
        .then(segments => {
            var uriList = segments.map(segment => URLToolkit.buildAbsoluteURL(url, segment.uri, { alwaysNormalize: true }))
            // console.log(uriList)
            return uriList
        })
        .then(uriList => {
            return uriListToBuffer(uriList)
        })
        .then(u8s => {
            // console.log(u8s)
            return u8sToFmp4(u8s)
        })
        .then(fmp4 => {
            var blob = new Blob([fmp4.initSegment, fmp4.data], {type: 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'})
            var url = URL.createObjectURL(blob)
            console.log(url, blob)
            var a = document.createElement('a')
            a.setAttribute('href', url)
            a.setAttribute('download', 'output.mp4')
            a.textContent = '点击下载'
            document.body.appendChild(a)

            // var mediaSource = new MediaSource()
            // video.src = URL.createObjectURL(mediaSource)
            // mediaSource.addEventListener('sourceopen', function (e  ) {
            //     var mime = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'
            //     var mediaSource = e.target
            //     var sbf = mediaSource.addSourceBuffer(mime)
            //     sbf.addEventListener('updatend', )
            // }, { once : true})
            // window.open(url)
            video.src = url
            video.controls = true
        })
 }

 function uriListToBuffer (uriList) {
     
     return new Promise((resolve, reject) => {
        var promises = uriList.map(uri => fetch(uri).then(response => response.arrayBuffer()))
        Promise.all(promises).then(buffers => {
            return buffers.map(bf => new Uint8Array(bf))
        })
        .then(u8s => resolve(u8s))
     })
 }

 function u8sToFmp4 (u8s) {
    var transmuxer = new muxjs.mp4.Transmuxer();

    return new Promise((resolve, reject) => {
        transmuxer.on('data', segment => {
            resolve(segment)
        })
        transmuxer.on('done', dd => {
            console.log('done', dd)
        })
        u8s.map(u8 => {
            console.log('u8', u8)
            var res = transmuxer.push(u8)
        })
        transmuxer.flush()
    })
 }
